package com.properties;

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/26 10:42
 * @since JDK 1.8
 *
 * 配置文件信息初始化工具类
 */
public class ProPertiesUtils {

    /**
     *
     * @param propertiesName 配置文件名称
     * @param stringStringMap
     */
    public static void loadProperties(String propertiesName, Map<String, String> stringStringMap) {
        // 获得PathMatchingResourcePatternResolver对象
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            // 加载resource文件(也可以加载resources)
            Resource resources = resolver.getResource("classpath:"+propertiesName+".properties");
            PropertiesFactoryBean config = new PropertiesFactoryBean();
            config.setLocation(resources);
            config.afterPropertiesSet();
            Properties prop = config.getObject();
            // 循环遍历所有得键值对并且存入集合
            for (String key : prop.stringPropertyNames()) {
                stringStringMap.put(key, (String) prop.get(key));
            }
        } catch (Exception e) {
            new Exception("配置文件加载失败");
        }
    }

    public static void main(String[] args) {
        Map<String, String> map=new HashMap<>();
        loadProperties("sql",map);
        map.forEach((k,v)->{
            System.out.println(k+" "+v);
        });
    }

    /**
     * 从其他路径加载配置文件
     * @param file
     * @param stringStringMap
     */
    public static void loadProperties(File file,Map<String, String> stringStringMap){
             Properties properties = new Properties();
             try {
                 // 使用InPutStream流读取properties文件
                 BufferedReader bufferedReader = new BufferedReader(new FileReader(file.getPath()));
                 properties.load(bufferedReader);
                 // 获取key对应的value值
                 properties.forEach((k,v)->{
                     stringStringMap.put(String.valueOf(k),String.valueOf(v));
                 });
             }catch (Exception e){
                 e.printStackTrace();
             }

    }


}
